package com.webull.information.center.carwler.job;

import java.net.InetAddress;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.webull.information.center.carwler.common.model.CollectRecord;
import com.webull.information.center.carwler.common.model.parm.CollectParm;
import com.webull.information.center.carwler.common.util.eljob.ElasticJobUtil;
import com.webull.information.center.carwler.dao.CollectRecordDao;
import com.webull.information.center.carwler.task.News_CNBC_UsStock_Task;
import com.webull.securities.client.model.Exchange;
import com.webull.securities.client.model.parm.ExchangeParam;
import com.webull.securities.client.service.ExchangeService;

/**
 * 美股采集cnbc的源
 *
 * @author shimingjun
 * @version 1.0
 * @date 2017年3月2日 下午3:18:47
 * @since JDK 1.8
 */
@Component
public class News_CNBC_US_Stock_Job implements SimpleJob {
    protected final Logger logger = LogManager.getLogger(getClass());
    private @Autowired
    News_CNBC_UsStock_Task fullStockFinanceNews;
    private @Autowired
    ExchangeService exchangeService;
    private @Autowired
    CollectRecordDao collectRecordDao;
    private final String collectJob = "News_CNBCStock_Job";
    // private final Integer loop = 50;// 循环20次退出,获取 20*100

	@Override
	public void execute(ShardingContext context) {
		int sharding = Optional.ofNullable(context).map(v -> v.getShardingItem()).orElse(-1);
		int totalCount = Optional.ofNullable(context).map(v -> v.getShardingTotalCount()).orElse(-1);

		logger.info("News_CNBCStock_Job start:" + ArrayUtils.toString(sharding) + ",totalCount:" + totalCount);
		ExchangeParam exchangeParam = new ExchangeParam();
		exchangeParam.setRegionId(6);
		List<Exchange> exchanges = exchangeService.search(exchangeParam);
		logger.info("News_CNBCStock_Job div size{};exchanges:{};", exchanges != null ? exchanges.size() : 0,
				ArrayUtils.toString(exchanges));
		List<Exchange> shardExchanges = Optional.ofNullable(ElasticJobUtil.shardingItems(context, exchanges))
				.orElse(exchanges);

		process_0(shardExchanges);
	}


    public void process_0(List<Exchange> shardExchanges) {
        Collections.shuffle(shardExchanges);
        logger.info("News_CNBCStock_Job div size{};shardExchanges:{};",
                shardExchanges != null ? shardExchanges.size() : 0, ArrayUtils.toString(shardExchanges));
        for (int i = 0; shardExchanges != null && i < shardExchanges.size(); i++) {
            try {
                List<CollectRecord> records = collectRecordDao.search(collectParm(shardExchanges.get(i)));
                Integer lastId = getLastTickeId(records);
                logger.info("News_CNBCStock_Job shardExchanges start collectJob{} div ,exchange:{},lastId{}",
                        collectJob, shardExchanges.get(i).getExchangeCode(), lastId);
                Integer lastId_ = fullStockFinanceNews
                        .stockFinanceNewsExchangeCode(shardExchanges.get(i).getExchangeCode(), lastId, null);
                CollectRecord record = backRecord(shardExchanges.get(i));
                record.setLastTickerId(lastId_);
                Integer collId = collectRecordDao.add(record);
                logger.info("News_CNBCStock_Job shardExchanges end collectJob{} div ,exchange:{},collId{}", collectJob,
                        shardExchanges.get(i).getExchangeCode(), collId);
            } catch (Exception e) {
                logger.error("News_CNBCStock_Job shardExchanges collectJob div error:" + shardExchanges.get(i), e);
            }
        }
    }

    private Integer getLastTickeId(List<CollectRecord> records) {
        if (records == null || records.isEmpty()) {
            return -1;
        } else {
            return records.get(0).getLastTickerId();
        }
    }

    private CollectParm collectParm(Exchange exchange) {
        CollectParm parm = new CollectParm();
        parm.setCollectJob(collectJob);
        parm.setExchangeCode(exchange.getExchangeCode());
        parm.setExchangeId(exchange.getId());
        parm.setRecordType(CollectRecord.RecordTypeConstants.NEWS);
        return parm;
    }

    private CollectRecord backRecord(Exchange exchange) {
        CollectRecord record = new CollectRecord();
        record.setCollectJob(collectJob);
        record.setExchangeCode(exchange.getExchangeCode());
        record.setExchangeId(exchange.getId());
        record.setRecordType(CollectRecord.RecordTypeConstants.NEWS);
        try {
            record.setCustomer(InetAddress.getLocalHost().getHostAddress());
        } catch (Exception e) {
        }
        return record;
    }

}
